package com.writing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.writing.entity.ApiConfig;
import com.writing.mapper.ApiConfigMapper;
import com.writing.service.ApiConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * API配置服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ApiConfigServiceImpl implements ApiConfigService {

    private final ApiConfigMapper apiConfigMapper;

    @Override
    public List<ApiConfig> getConfigsByUserId(Long userId) {
        LambdaQueryWrapper<ApiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApiConfig::getUserId, userId)
               .orderByDesc(ApiConfig::getUpdatedAt);
        return apiConfigMapper.selectList(wrapper);
    }

    @Override
    public ApiConfig getConfigById(Long id) {
        return apiConfigMapper.selectById(id);
    }

    @Override
    public List<ApiConfig> getAllConfigs() {
        LambdaQueryWrapper<ApiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(ApiConfig::getEnabled)
               .orderByDesc(ApiConfig::getUpdatedAt);
        return apiConfigMapper.selectList(wrapper);
    }

    @Override
    public List<ApiConfig> getEnabledConfigs() {
        LambdaQueryWrapper<ApiConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApiConfig::getEnabled, 1)
               .orderByDesc(ApiConfig::getUpdatedAt);
        return apiConfigMapper.selectList(wrapper);
    }

    @Override
    @Transactional
    public ApiConfig createConfig(ApiConfig apiConfig) {
        // 设置默认值
        // 管理员创建的配置默认启用，所有用户都可以使用
        if (apiConfig.getEnabled() == null) {
            apiConfig.setEnabled(1); // 默认为启用状态
        }
        if (apiConfig.getTemperature() == null) {
            apiConfig.setTemperature(new BigDecimal("0.7"));
        }
        if (apiConfig.getTopP() == null) {
            apiConfig.setTopP(new BigDecimal("1.0"));
        }
        if (apiConfig.getFrequencyPenalty() == null) {
            apiConfig.setFrequencyPenalty(new BigDecimal("0.0"));
        }
        if (apiConfig.getPresencePenalty() == null) {
            apiConfig.setPresencePenalty(new BigDecimal("0.0"));
        }
        if (apiConfig.getTimeout() == null) {
            apiConfig.setTimeout(30);
        }
        if (apiConfig.getStreamMode() == null) {
            apiConfig.setStreamMode(1);
        }
        if (apiConfig.getRetryCount() == null) {
            apiConfig.setRetryCount(3);
        }
        if (apiConfig.getEnabled() == null) {
            apiConfig.setEnabled(1);
        }

        apiConfig.setCreatedAt(LocalDateTime.now());
        apiConfig.setUpdatedAt(LocalDateTime.now());

        apiConfigMapper.insert(apiConfig);
        return apiConfig;
    }

    @Override
    @Transactional
    public ApiConfig updateConfig(ApiConfig apiConfig) {
        apiConfig.setUpdatedAt(LocalDateTime.now());
        apiConfigMapper.updateById(apiConfig);
        return apiConfig;
    }

    @Override
    @Transactional
    public void deleteConfig(Long id) {
        apiConfigMapper.deleteById(id);
    }

    @Override
    @Transactional
    public ApiConfig duplicateConfig(Long configId) {
        ApiConfig originalConfig = apiConfigMapper.selectById(configId);
        if (originalConfig == null) {
            throw new RuntimeException("原配置不存在");
        }

        ApiConfig newConfig = new ApiConfig();
        newConfig.setUserId(originalConfig.getUserId());
        newConfig.setName(originalConfig.getName() + " - 副本");
        newConfig.setType(originalConfig.getType());
        newConfig.setApiKey(originalConfig.getApiKey());
        newConfig.setBaseUrl(originalConfig.getBaseUrl());
        newConfig.setSelectedModel(originalConfig.getSelectedModel());
        newConfig.setMaxTokens(originalConfig.getMaxTokens());
        newConfig.setUnlimitedTokens(originalConfig.getUnlimitedTokens());
        newConfig.setTemperature(originalConfig.getTemperature());
        newConfig.setTopP(originalConfig.getTopP());
        newConfig.setFrequencyPenalty(originalConfig.getFrequencyPenalty());
        newConfig.setPresencePenalty(originalConfig.getPresencePenalty());
        newConfig.setTimeout(originalConfig.getTimeout());
        newConfig.setStreamMode(originalConfig.getStreamMode());
        newConfig.setRetryCount(originalConfig.getRetryCount());
        newConfig.setCustomHeaders(originalConfig.getCustomHeaders());
        newConfig.setDescription(originalConfig.getDescription());
        newConfig.setEnabled(0); // 副本默认禁用
        newConfig.setCreatedAt(LocalDateTime.now());
        newConfig.setUpdatedAt(LocalDateTime.now());

        apiConfigMapper.insert(newConfig);
        return newConfig;
    }

    @Override
    public boolean testConnection(ApiConfig config) {
        try {
            // 这里实现API连接测试逻辑
            // 可以发送一个简单的请求来测试连接
            log.info("测试API配置连接: {}", config.getName());
            
            // TODO: 实现实际的连接测试逻辑
            // 例如调用 /models 接口或发送一个简单的聊天请求
            
            return true; // 暂时返回true，实际应该根据测试结果返回
        } catch (Exception e) {
            log.error("API配置连接测试失败: {}", e.getMessage());
            return false;
        }
    }
}
